
<template>
  <div class="invoicelist">
    <div class="flex flex-jus-between" style="padding:0 0.25rem 0 0">
      <div class="apptitle"><!-- 发票夹 --></div>
      <div class="menubtn" @click="openscreen">
        <img src="../assets/icon-menu.svg">
      </div>
    </div>
    
    <!-- 顶部弹出窗 -->
    <van-popup v-model="screenshow" position="top" :style="{ height: '7.5rem' }" >
      <div class="screentitle flex flex-jus-start">
        <div style="margin-right: .4rem;">
          条件筛选 
        </div>
      </div>
      <div class="time-type">
        <dl>
          <dt class="flex flex-jus-start">
            开票日期 
            <div class="timerange">
              <span @click="timeRage('week')">近一周</span>
              <span @click="timeRage('month')">近一月</span>
              <span @click="timeRage('year')">近一年</span>
            </div>
          </dt>
          <dd class="flex flex-jus-start">
            <span @click="screentimeselectHand(1)">{{ invoiceStartTime || '选择日期' }}</span> 到 <span @click="screentimeselectHand(2)">{{ invoiceEndTime || '选择日期' }}</span>
          </dd>
        </dl>
        <dl>
          <dt>选择类型</dt>
          <dd class="flex flex-jus-start">
            <span @click="screentypeselect = true" style="margin-left:0;">{{ screentype }}</span>
          </dd>
        </dl>
        <dl>
          <dt>选择状态</dt>
          <dd class="flex flex-jus-start">
            <span @click="screenstateselect = true" style="margin-left:0;">{{ screenstate }}</span>
          </dd>
        </dl>
        <div class="flex flex-jus-end" style="margin-top: .3rem;">
          <span @click="resetInvoicetj" style="margin-right: 0.3rem;color:#7084ff">点击重置</span>
          <van-button type="primary" square @click="screenDataList" size="middle" color="#7084ff">确定</van-button>
        </div>
      </div>
    </van-popup>
    <van-popup v-model="screenstateselect" position="bottom" :style="{ height: '4.5rem' }" >
      <van-picker
        show-toolbar
        title="状态"
        :columns="['未核销','冻结','已核销',]"
        @cancel="onCancel"
        @confirm="onConfirmState"
      />
    </van-popup>
    <van-popup v-model="screentypeselect" position="bottom" :style="{ height: '4.5rem' }" >
      <van-picker
        show-toolbar
        title="标题"
        :columns="columns"
        @cancel="onCancel"
        @confirm="onConfirm"
      />
    </van-popup>
    <van-popup v-model="screentimeselect" position="bottom" :style="{ height: '4.5rem' }" >
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="onCancel"
        @confirm="onConfirmTime"
      />
    </van-popup>

    <!-- <div style="height:1rem"></div> -->
    <div class="totalprize">
      总额 :
      <span>{{ totalPrice.toFixed(2) }}</span>
    </div>
    <van-row>
      <van-col span="1"></van-col>
      <van-col span="22">

        <ul class="list">
          <li v-for="item in items" :key="item.index" >
            <div class="invoicetype flex">
              <img src="../assets/icon-yz.svg" />
              <!-- "billingDate": "2023-12-16", 开票时间
              "entryTime": "2024-03-13 10:58:47", 录入时间
              "invoiceNumber": "A000497",税号
              "invoiceCode": "33400301031217A000497"税码
              checkStatus 0未查验，1有效已查验，2有效未查验，3无效
              imageDocId  null-手动添加 不为null-识别成功
              category 分类
              status 0-未核销 1-冻结 2-已核销 -->
              <div @click="goLink(item)" >{{ item.category }}</div>
            </div>
            <div class="text">
              <div  @click="goLink(item)" class="type" >
                <p  v-if="item.checkStatus == 0" class="van-color-text-secondary line-height-class">未查验</p>
                <p v-if="item.checkStatus == 1" class="van-color-primary line-height-class">有效已查验</p>
                <p v-if="item.checkStatus == 2" class="van-color-primary line-height-class">有效未查验</p>
                <p v-if="item.checkStatus == 3" class="van-color-text-secondary line-height-class">无效</p>
                <p v-if="item.status == 0" class="van-color-text-secondary line-height-class">未核销</p>
                <p v-if="item.status == 1" class="van-color-danger line-height-class">冻结</p>
                <p v-if="item.status == 2" class="van-color-text-secondary line-height-class">已核销</p>
              </div>
              <div @click="goLink(item)" class="prize"  >
                CNY : <span>{{ (item.taxincludedprice || item.fare || item.totalAmount || item.Amount || 0).toFixed(2) }}</span>
              </div>
              <p  @click="goLink(item)" class="title" >{{ item.category }}</p>
              <p  @click="goLink(item)" class="van-color-text-secondary">流程编号 : {{ item.requestId }}</p>
              <p  @click="goLink(item)" class="van-color-text-secondary">开票时间 : {{ item.billingDate }}</p>
              <p  @click="goLink(item)" class="van-color-text-secondary">发票号 : {{ item.invoiceNumber }}</p>
              <p  @click="goLink(item)" class="van-color-text-secondary">销售方 : {{ item.seller }}</p>
              <p  @click="goLink(item)" class="van-color-text-secondary">购买方 : {{ item.purchaser }}</p>
              <!-- <p class="van-color-text-secondary flex flex-jus-start">
                添加方式 :
                <img class="addfunc" v-if="item.imageDocId" src="../assets/icon-camera-black.svg">
                <img class="addfunc edit" v-else src="../assets/icon-edit-black.svg">
              </p>
              <p class="van-color-text-secondary">是否编辑过 : {{ item.updateOperate == 0 ? "未编辑过":"已编辑过" }}</p> -->
              <p  @click="goLink(item)" class="van-color-text-secondary">备注 : {{ item.remark }}</p>
              <p class="flex flex-jus-start m-t-15">
                <!-- 添加方式 有值则表示未拍照上传 -->
                <img class="addfunc" v-if="item.imageDocId" src="../assets/icon-camera2.svg">
                <img class="addfunc" v-else src="../assets/icon-camera2-black.svg">
                <img class="delfun" @click="deleteBtn(item)" src="../assets/delete.svg">
                <!-- 是否编辑过 0表示未编辑过 -->
                <img class="addfunc" @click="goLink(item)"  v-if="item.updateOperate != 0" src="../assets/icon-edit2.svg">
                <img class="addfunc" @click="goLink(item)" v-else src="../assets/icon-edit2-black.svg">
              </p>
            </div>
          </li>
        </ul>
        <infinite-loading @infinite="updateList">
          <div slot="spinner">加载中...</div>
          <div slot="no-more">没有更多了</div>
          <div slot="no-results">没有更多了</div>
        </infinite-loading>
      </van-col>
      <van-col span="1"></van-col>
    </van-row>

  </div>
</template>

<script>
import InfiniteLoading from 'vue-infinite-loading';
import { getListRecord,delInvoice } from '../plugins/api'
import { Toast,Dialog } from 'vant-green'
import { mapMutations } from 'vuex'
export default {
  name: 'InvoiceListView',
  data(){
    return {
      totalPrice:0, //总额
      screenshow:false, // 条件选择框是否显示
      screentimeselect:false, // 时间选择是否显示
      screentypeselect:false, // 发票类型是否显示
      screentype:"全部",    // 发票类型的值
      screenstate:'未核销', // 发票状态
      defaultValue:'',
      // 时间段选择器
      value: "", // 时间默认值
      showPicker: false,
      minDate: new Date(2023, 1, 1),
      maxDate: new Date(2040, 12, 31),
      currentDate: new Date(),
      startDate: '',
      endDate: '',
      invoiceStartTime: '',
      invoiceEndTime: '',
      columns:[], //类型选择
      items: [], // 数据列表
      currentPage:1, // 当前页码
      totalPages:1, // 总页码
      size:10, // ,每页条数
      hasMore:true, // 当前加载状态状态
      screenstateselect:false, // 发票状态
    }
  },
  components:{InfiniteLoading},
  methods:{
    ...mapMutations(['setFullLoading']),
    //时间段选择
    timeRage(range){
      // 当前时间戳 
      const nowDate = new Date();
      const year    = nowDate.getFullYear();
      const month   = (nowDate.getMonth() + 1).toString().padStart(2, '0');
      const day     = nowDate.getDate().toString().padStart(2, '0');
      let [endYear,endMonth,endDay,endDate]   = ["","","",""];
      switch(range){
        case 'week':
          console.log('week');
          endDate = new Date(Date.now() - 7 * 24 * 3600 * 1000);
          break;
        case 'month':
          console.log('month');
          endDate = new Date(Date.now() - 30 * 24 * 3600 * 1000);
          break;
        case 'year':
          console.log('year');
          endDate = new Date(Date.now() - 365 * 24 * 3600 * 1000);
          break;
        default:
          break;
      }
      endYear    = endDate.getFullYear();
      endMonth   = (endDate.getMonth() + 1).toString().padStart(2, '0');
      endDay     = endDate.getDate().toString().padStart(2, '0');
      this.invoiceStartTime = `${endYear}-${endMonth}-${endDay}`;
      this.invoiceEndTime = `${year}-${month}-${day}`;
    },
    goLink(item={}){
      console.log("接收来的参数:",item);
      this.$router.push({path:'/invoiceInfo',query:item})
    },
    deleteBtn(item={}){
      let that =this
      console.log("接收来的参数:",item);
      Dialog.confirm({
        message: '是否确认删除该发票？'
      }).then(() => {
        let userId = localStorage.getItem('userId');
        delInvoice({"id":item.id,"delBy":userId}).then(res=>{
          console.log("del=>update",res);
        
          if(res.code==200){
            that.currentPage =1
            Toast(res.msg)
            that.updateList()
          }else{
            Toast(res.msg)
          }
        })
      }) .catch(() => {
        // on cancel
      });;
    },
    openscreen(){
      this.screenshow = true
      console.log("打开筛选");
    },
    // 类型选择
    onConfirm(value, index) {
      console.log(`onConfirm当前值：${value}, 当前索引：${index}`);
      this.screentype = value
      this.screentypeselect = false
    },
    onCancel() {
      this.screentypeselect  = false
      this.screentimeselect  = false
      this.screenstateselect = false
    },

    onConfirmState(value,index){
      this.screenstate = value
      this.screenstateselect = false
    },
    // 时间选择插件的确定事件
    onConfirmTime(value) {
      // console.log(`onConfirm当前值：${value}, 当前索引：${index}`);
      const date    = new Date(value);
      const year    = date.getFullYear();
      const month   = (date.getMonth() + 1).toString().padStart(2, '0');
      const day     = date.getDate().toString().padStart(2, '0');
      switch(this.timeIndex){
        case 1:
          this.invoiceStartTime = `${year}-${month}-${day}`;
          break;
        case 2:
          this.invoiceEndTime   = `${year}-${month}-${day}`;
          break;
        default:
          break;
      }
      this.screentimeselect = false
    },
    screentimeselectHand(num){
      this.timeIndex = num
      this.screentimeselect = true
    },
    buling(num){
      return num < 10 ? '0' + num : num
    },
    resetInvoicetj(){
      console.log('重置');
      this.invoiceStartTime = ''
      this.invoiceEndTime   = ''
      this.screentype       = "全部"
      this.screenstate      = '未核销'
      this.screenshow       = false
      this.items            = []
      this.currentPage      = 1
      this.totalPages       = 1
      this.size             = 10

      // 如果为true则是没有全部加载完就点击了重置
      if(this.hasMore || this.items.length <= 0){ // || this.list
        this.updateList()
      }else{
        this.state.reset()
      }
    },
    // 带筛选条件的搜索
    screenDataList(){

      this.items            = []
      this.currentPage      = 1
      this.totalPages       = 1
      this.size             = 10

      // 如果为true则是没有全部加载完就点击了搜索
      if(this.hasMore || this.items.length <= 0){
        this.updateList()
      }else{
        this.state.reset()
      }
    },
    updateList($state){
      console.log("更新列表");
      console.log("this.currentPage ",this.currentPage );
      console.log("this.totalPages",this.totalPages);
      this.state = $state
      // 筛选条件更新列表
      // 隐藏筛选框
      this.screenshow = false

      // 如果索引超过当前总页码则停止
      if(this.currentPage > this.totalPages){
        this.hasMore = false;
        if($state)$state.complete();
        return false;
      }
      // 下拉加载更多处理函数 
      // 默认获取第一页数据
      let a = 0
      if(this.screenstate == '已核销'){
        a = 2
      }else if(this.screenstate == '冻结'){
        a = 1
      }else{
        a = 0
      }
      let formData = new FormData()
          formData.append('type',this.screentype == "全部"?"":this.screentype) // 类型
          formData.append('state',a) // 类型
          formData.append('page',this.currentPage) // 请求页码
          formData.append('size',this.size) // 每页长度
          formData.append('userId',localStorage.getItem('userId')) // 用户ID
          formData.append('beginTime',this.invoiceStartTime) // 开票时间
          formData.append('finishTime',this.invoiceEndTime) // 开票结束时间
        console.log("筛选条件:",formData)
      getListRecord(formData).then(res=>{
        console.log(res);
        if(res.code == 200){
          this.totalPrice = res.data.totalPrice || 0 // 总金额
          this.totalPages = res.data.totalPages // 总页数
          if(res.data.record.length > 0){
            
            this.items = this.currentPage==1?this.items=res.data.record : this.items.concat(res.data.record); // 获取来的列表数据
            console.log(this.items);
            this.currentPage++
            this.hasMore = true;
            if($state)$state.loaded();
          }else{
            this.hasMore = false;
            this.items=[]
            if($state)$state.complete();
            Toast('没有更多了!')
          }

        }else{
          // if($state.complete)$state.complete();
          Toast(res.msg)
        }
      }).catch(err=>{
        // if($state.complete)$state.complete()
        Toast(err.errMsg)
      })
    },
  },
  //设置title的钩子
  beforeRouteEnter(to, from, next) {
    document.title = to.meta.title || 'Default Title';
    next();
  },
  beforeRouteUpdate(to, from, next) {
    document.title = to.meta.title || 'Default Title';
    next();
  },
  mounted(){
    this.$store.commit('setFullLoading',false);
    // 默认时间
    let nowTime = new Date()
    this.value = `${nowTime.getFullYear()}-${this.buling(nowTime.getMonth()+1)}-${this.buling(nowTime.getDate())}至${nowTime.getFullYear()}-${this.buling(nowTime.getMonth()+1)}-${this.buling(nowTime.getDate())}`
    // 条件
    this.columns.push('全部')
    this.$store.state.billTypeLists.map(v=>{
      this.columns.push(v.label)
    })
  }
}
</script>

<style scoped>
  ul.list {
    padding-top: .2rem;
  }
  ul.list li {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 .06rem .23rem rgba(103, 124, 253, 0.3);
    padding:.25rem;
    line-height: 1.6;
    border-radius: .18rem;
    margin-bottom: .35rem;
    position: relative;
  }
  ul.list li .text {
    flex:1;
    font-size: .28rem;
    position: relative;
  }
  ul.list li .text .type {
    position: absolute;
    right:0;
    top:0;
    font-size: .28rem;
    opacity: .5;
    line-height: 1;
  }
  ul.list li .text .prize {
    position: absolute;
    right:0rem;
    bottom:0rem;
    font-size: .3rem;
    line-height: 1;
    color:#999;
    letter-spacing: -0.02rem;
  }
  ul.list li .text .prize span {
    font-size: .5rem;
    font-weight: bold;
    font-family: Arial, Helvetica, sans-serif;
    color:#333;
  }
  .van-cell {
    border:.01rem solid #eee;
    border-radius: .05rem;
    margin-top: .3rem;
  }
  .van-picker-column__item--selected {
    font-size: .28rem;
  }
  .invoicelist {
    font-size: .26rem;
    /* color:#999; */
    /* padding-top: .1rem; */
    padding-bottom: 0;
  }
  .title {
    line-height: 1!important;
    font-size: .34rem;
    margin-bottom: .35rem;
    width: 65%;
    overflow:hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .invoicetype {
  width: 2.2rem;
  height:1.7rem;
  position: absolute;
  right:.6rem;
  top:.2rem;
  transform: rotate(20deg);
  overflow-y: hidden;
  opacity: .3;
}
.invoicetype div {
  font-size: .26rem;
  color:#E03353;
}
.invoicetype img {
  width: 100%;
  position: absolute;
  left:0;
  top:-0.25rem;
}
.invoicelist {
  position: relative;
}
.invoicelist .menubtn {
  width:.6rem;
  opacity: .7;
}
.invoicelist .menubtn img {
  display: block;
  width: 100%;
}
.screentitle {
  font-size: .3rem;
  padding:.25rem .25rem 0;
  color:#333;
}
.time-type {
  font-size: .28rem;
  padding:.35rem .35rem 0;
}
.time-type dl {
  font-size: .3rem;
  padding:.1rem;
  margin-bottom: 0.05rem;
  color:#888;
}
.time-type dt {
  margin-bottom: .18rem;
}

.time-type dd span {
  background-color: #F6F7FC;
  padding:0.1rem 0.25rem;
  min-width: 2.5rem;
  text-align: center;
}
.time-type dd span:first-child {
  margin-right: 0.2rem;
}
.time-type dd span:last-child {
  margin-left: 0.2rem;
}
.timerange span {
  color:rgb(112, 132, 255);
  margin-left:0.25rem;
  text-decoration: underline;
  font-size: 0.24rem;
}
.addfunc {
  display: block;
  width: .5rem;
  margin-right:.2rem;
  opacity: .7;
}
.delfun {
  display: block;
  width: .36rem;
  margin-right:.2rem;
  opacity: .7;
}
.totalprize {
  position: fixed;
  right:0.2rem;
  bottom:1.3rem;
  z-index: 9;
  padding:.15rem .35rem;
  box-shadow: 0 0 0.2rem rgba(103, 124, 253, 0.3);
  background: white;
  border-radius: 0.2rem;
  font-size: .3rem;
  color:#666;
}
.totalprize span {
  font-size: .44rem;
  font-weight: bold;
  color:#333;
  vertical-align: -0.02rem;
}
.infinite-loading-container {
  font-size: .2rem;
  color:#999;
}
.m-t-15 {
  margin-top: .15rem;
}
.line-height-class {
  line-height: 1.5; font-size: .25rem;
}
</style>